package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminMapper;
import com.heima.admin.service.AdService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdServiceImpl extends ServiceImpl<AdminMapper, AdUser> implements AdService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public ResponseResult login(AdUserDto dto) {
        //真正的用户登录
        //验证参数中的用户名和密码是否为空
        if (StringUtils.isNotEmpty(dto.getName()) && StringUtils.isNotEmpty(dto.getPassword())) {
            //通过同户名查询用户的数据
            AdUser adUser = adminMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
            //如果数据为空返回1002
            if (null == adUser) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //如果用户存在则获取数据中的slat 然后使用md5重新对数据进行加密
            String salt = adUser.getSalt();
            String saltPassword = dto.getPassword() + salt;
            saltPassword = DigestUtils.md5DigestAsHex(saltPassword.getBytes());
            //比对2个密文的密码如果成功则生成token并返回如果失败则返回密码错误的提示
            if (saltPassword.equals(adUser.getPassword())) {
                String token = AppJwtUtil.getToken((long) adUser.getId());

                adUser.setSalt("");
                adUser.setPassword("");

                Map<String, Object> map = new HashMap<>();
                map.put("user", adUser);
                map.put("token", token);

                return ResponseResult.okResult(map);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            //游客登录
            String token = AppJwtUtil.getToken(0l);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }
}
